/**
 * Author: w景洋.
 * Time: 2016/7/6 0006
 */
angular.module('entrance.md.home', [

    ])

    .config(['$stateProvider',   '$urlRouterProvider',
        function($stateProvider, $urlRouterProvider) {
            $stateProvider
            .state('model.home', {
                url : '/home',
                templateUrl :entrance_templateprefix + 'connect/home.html',
                controller : 'HomeController'
            })
            .state('model.scgy', {
                 url : '/scgy',
                 templateUrl : entrance_templateprefix+'cmt_mall/scgy.html',
                 controller : 'ScgyController'
            })

        }])


    .controller('HomeController', ['$scope', '$state','$localStorage','Entrance_HomeService','Entrance_WpzrService','Entrance_ShopService', function($scope,$state,$localStorage,Entrance_HomeService,Entrance_WpzrService,Entrance_ShopService) {
        search_top();
        slid("slider");
        //缓存
        var $storage = $localStorage.$default({
            cmtcity: '',
            cmtscope: ''
        });

        //定位
        EnterChange(1);
        mapObj = new AMap.Map('iCenter');//定义地图容器
        if($storage.cmtcity == ""){
            $scope.i = 0;//用于ng-show
        }else{
            $scope.city =$storage.cmtcity;
            $scope.i = 1;
        }


        //定位坐标转换

        //var Longitude=102.999,Latitude=103;
        var startLongitude = 119.040202, andLongitude = 119.622016, startLatitude = 25.90586, andLatitude = 26.198767;
        var diffLongitude = andLongitude - startLongitude,diffLatitude = andLatitude-startLatitude;
        var blockNumber = 3,scope='',number = 0,blockLongitude,blockLatitude,maxNumber=4;
        var block = [[1,4,7],[2,5,8],[3,6,9]];
        $scope.getPosition= function (Longitude,Latitude){
            var i= 0,j=0;
            blockLongitude = diffLongitude/blockNumber;
            blockLatitude = diffLatitude/blockNumber;
            for(i = 0;i<blockNumber;i++){
                for (j=0;j<blockNumber;j++){
                    if((Longitude>=startLongitude+blockLongitude*i&&Longitude<startLongitude+blockLongitude*(i+1))
                        &&(Latitude>=startLatitude+blockLatitude*j&&Latitude<startLatitude+blockLatitude*(j+1))){
                        scope += block[i][j]+"";
                        console.log(scope)
                        startLongitude=startLongitude+blockLongitude*i;
                        startLatitude=startLatitude+blockLatitude*j;
                        diffLongitude=blockLongitude;
                        diffLatitude=blockLatitude;
                        number++;
                        if(number>=maxNumber){

                            $storage.cmtscope = scope;
                            //$storage.scope = $scope.area;
                            startLongitude = 119.040202, andLongitude = 119.622016, startLatitude = 25.90586, andLatitude = 26.198767;
                            diffLongitude = andLongitude - startLongitude, diffLatitude = andLatitude - startLatitude;
                            blockNumber = 3, scope = '', number = 0, blockLongitude, blockLatitude, maxNumber = 4;
                        }
                        else{
                            $scope.getPosition(Longitude,Latitude);
                        }
                    }
                }
            }
        }

        //地图定位
        var prompt = "";
        var lng = "";
        var lat = "";
        mapObj.plugin('AMap.Geolocation', function () {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 1000,          //超过10秒后停止定位，默认：无穷大
                maximumAge: 0,           //定位结果缓存0毫秒，默认：0
                convert: false,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                showButton: false,        //显示定位按钮，默认：true
                //buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
                //buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                showMarker: false,        //定位成功后在定位到的位置显示点标记，默认：true
                showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
                panToLocation: false,     //定位成功后将定位到的位置作为地图中心点，默认：true
                zoomToAccuracy:false      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            });
            mapObj.addControl(geolocation);
            geolocation.getCurrentPosition();
            AMap.event.addListener(geolocation, 'complete',function(data){
                lng = data.position.getLng();//lng、lat分别代表经度、纬度值
                lat = data.position.getLat();
                prompt = '经度：'+ lng +'纬度：'+ lat;
                console.log(prompt)
                $scope.getPosition(lng,lat);
                Entrance_HomeService.getLocation(lng,lat).$promise.then(function(data){


                    if($storage.cmtcity == ""){
                        $scope.city = data.regeocode.addressComponent.city;
                        $storage.cmtcity = $scope.city;//把所在市存在缓存中
                        $scope.i = 1;
                    }else{
                        $scope.NewCity = data.regeocode.addressComponent.city;
                        //判断位置是否发送了变化
                        if($storage.cmtcity != $scope.NewCity){
                            $scope.city = $scope.NewCity;
                            $storage.cmtcity = $scope.NewCity;
                        }
                    }
                })
            });//返回定位信息
            AMap.event.addListener(geolocation, 'error', function(data){
                alert(data.info)
                $scope.i = 2;
                switch(data.info) {
                    case 'PERMISSION_DENIED':
                        alert('浏览器阻止了定位操作') ;
                        break;
                    case 'POSITION_UNAVAILBLE':
                        alert('无法获得当前位置');
                        break;
                    case 'TIMEOUT':
                        alert('定位超时');
                        break;
                    default:
                        alert('未知错误');
                        break;
                }
            });
        });

        //获取所有与的服务模块
        $scope.ent_mallurl = projectBaseUrl;
        Entrance_HomeService.allService().$promise.then(function(data){
            $scope.serlist = data;

        })
       //旺铺转让信息
       $scope.restalist = Entrance_WpzrService.getWpzrList();

        //跳转到食材供应
        $scope.scope = function(){
            Entrance_ShopService.queryShoplistByScope($storage.cmtscope).$promise.then(function(data){
                $scope.shoparea =data;
                console.log($scope.shoparea)
                alert($storage.cmtscope)
                if($storage.cmtscope == ""){
                    alert("定位中请稍后")
                }
                else if($scope.shoparea.length==0){
                    alert("该区域没有商家")
                }
                else{
                    $state.go("mall.bytag",{area:$storage.cmtscope});
                }
            })
        }
        //定位失败 重新定位
        $scope.onload = function(){
            $scope.i = 0;
            geolocation.getCurrentPosition();
        }
    }])
    .controller('ScgyController', ['$scope', '$state','Entrance_HomeService','Entrance_ShopService', function($scope,$state,Entrance_HomeService,Entrance_ShopService) {
        $scope.ent_mallurl = projectBaseUrl;
        EnterChange(1);
        Entrance_ShopService.getAllShopByTag().$promise.then(function(data){
            $scope.realweburl = realweburl;
            $scope.alltags = data;
            console.log(data)
        })
    }])